    package com.boot.springboot.service;

    import com.boot.springboot.pojo.Good;
    import com.boot.springboot.pojo.dto.GoodDto;
    import com.boot.springboot.repository.GoodRepository;
    import org.springframework.beans.BeanUtils;
    import com.boot.springboot.service.IGoodService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    import java.awt.geom.GeneralPath;
    import java.util.List;
    import java.util.Optional;

    @Service //spring的bean
    public class GoodService implements IGoodService {
        @Autowired
        GoodRepository goodRepository;
        @Override
        public Good add(GoodDto good) {
            Good goodPojo=new Good();
            BeanUtils.copyProperties(good,goodPojo);
            if (goodRepository.findByGoodId(goodPojo.getGoodId()).isPresent()) {
                throw new IllegalArgumentException("商品ID已存在：" + goodPojo.getGoodId());
            }
            return goodRepository.save(goodPojo);

        }

        @Override
        public Good get(Integer goodId) {
            return goodRepository.findByGoodId(goodId).orElseThrow(() -> {
                throw new IllegalArgumentException("不存在该商品，异常参数");
            });


        }

        @Override
        public Good edit(GoodDto good) {
            //先查询数据库中已存在的商品（通过goodId）
            Good goodPojo = goodRepository.findByGoodId(good.getGoodId())
                    .orElseThrow(() -> new IllegalArgumentException("商品不存在：" + good.getGoodId()));
            BeanUtils.copyProperties(good,goodPojo);
            return goodRepository.save(goodPojo);
        }

        @Transactional//JPA允许get方法通过非主键来进行查询，但detele不允许，所以为delete 方法开启一个数据库事务
        @Override
        public void delete(Integer goodId) {
            Good good = goodRepository.findByGoodId(goodId).orElseThrow(() -> new IllegalArgumentException("商品不存在，goodId：" + goodId));
            goodRepository.deleteByGoodId(goodId);
        }

        @Override
        public List<Good> getAllGoods() {
            return (List<Good>) goodRepository.findAll();
        }
    }
